'use strict'
const { Text, View, ScrollView } = window.QUI
import style from './css.css'
import asyncFetch from '../../utils/asyncFetch'
import queryString from 'query-string'
const urlData = queryString.parse(location.search)
console.log(process.env.NODE_ENV)
const reportType = (/article/).test(location.pathname) ? 1 : 0 // 举报类型 0为用户 1为糗事
const user = reportType === 0 ? '用户' : '糗事'
document.title = `举报${user}`
const qbtoken = process.env.NODE_ENV === 'development' ? 'e261a8dd6f196cca907c27e89b6f84134db0aea7' : urlData.token
const userid = process.env.NODE_ENV === 'development' ? '36462901' : urlData.userid
const arg = { 'qbtoken': qbtoken, 'userid': userid }
// const qbtoken = urlData.token
const reason = ['ad', 'porn', 'abusive', 'politic', 'other', 'not-qiushi', 'fen-qiushi']
class Index extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      imgSource: [],
      isSelsectType: false,
      typeNum: null,
      uptoken: null,
      reportImg: [],
      reportDetail: null,
      key: null
    }
    this.handleChange = this.handleChange.bind(this)
    this._handleImg = this._handleImg.bind(this)
    this._renderImgChoose = this._renderImgChoose.bind(this)
    this._handleDelate = this._handleDelate.bind(this)
    this._renderType = this._renderType.bind(this)
    this._handleSelectType = this._handleSelectType.bind(this)
    this._renderReportD = this._renderReportD.bind(this)
    this._getToken = this._getToken.bind(this)
    this._handleSubit = this._handleSubit.bind(this)
    this._renderUploadImg = this._renderUploadImg.bind(this)
    this._submitReportInfo = this._submitReportInfo.bind(this)
    this._ReportDetail = this._ReportDetail.bind(this)
    this.putb64 = this.putb64.bind(this)
  }
  componentDidMount () {
    this._getToken()
  }
  // 获取举报详情
  _ReportDetail (e) {
    this.setState({ reportDetail: e.target.value })
  }

  // 获取uptoken
  async _getToken () {
    const url = `${dataSource.api}/article/tokens?types=image`
    const res = await asyncFetch(url, arg)
    console.log(res)
    if (res.err === 0) {
      this.setState({ uptoken: res.tokens[0].token, key: res.tokens[0].key })
    }
    else {
      console.log(res)
    }
  }
  _inputBlur () {
    const { typeNum } = this.state
    if (!reportType || typeNum === 4) {
      const inputFocus = document.getElementById('input_id')
      inputFocus.blur()
    }
  }

  // 点击上传图片 在上传后台
  _handleSubit () {
    this._inputBlur()
    const { isSelsectType, imgSource, typeNum, uptoken } = this.state
    // alert(uptoken)
    if (!uptoken) {
      this._getToken()
    }
    if (!isSelsectType) {
      window.Qapp.showToast({ content: '请选择举报类型！' })
      return false
    }
    if (reportType === 1 && typeNum !== 6) {
      this._submitReportInfo()
      return false
    }
    if (imgSource.length === 0) { this._submitReportInfo() }
    for (let i = 0; i < imgSource.length; i++) {
      this.putb64(imgSource[i], imgSource.length, i)
    }
  }
  putb64 (imgSource, len, currLen) {
    window.Qapp.showLoad({ content: '上传图片中！' })
    const { uptoken } = this.state
    const str = imgSource.slice(0, imgSource.indexOf(',') + 1)
    const pic = imgSource.replace(str, '')
    const url = 'https://upload.qiniup.com/putb64/-1' // 非华东空间需要根据注意事项
    const xhr = new XMLHttpRequest()
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        const dataInfo = JSON.parse(xhr.response)
        if (dataInfo.error) { window.Qapp.showToast({ content: dataInfo.error }); return false }
        const { reportImg } = this.state
        reportImg.push(dataInfo.hash)
        this.setState({ reportImg })
        if (len === currLen + 1) {
          window.Qapp.hideLoad()
          this._submitReportInfo(reportImg)
        }
      }
    }

    xhr.open('POST', url, true)
    xhr.setRequestHeader('Content-Type', 'application/octet-stream')
    xhr.setRequestHeader('Authorization', `UpToken ${uptoken}`)
    xhr.send(pic)
  }

  // 提交举报信息
  async _submitReportInfo (reportImg) {
    const { typeNum, reportDetail } = this.state
    let obj
    if (reportType === 1) {
      obj = {
        method: 'POST',
        url: `${dataSource.api}${window.location.pathname}`,
        obj: {
          reason: reason[typeNum],
          pic_urls: reportImg,
          desc: reportDetail
        }
      }
    }
    else {
      obj = {
        method: 'POST',
        url: `${dataSource.api}${window.location.pathname}`,
        // url: 'https://m2.qiushibaike.com/article/120646066/report',
        obj: {
          reason: dataSource.reportUser[typeNum],
          pic_urls: reportImg,
          desc: reportDetail
        }
      }
    }
    // try {
    console.log('res')
    const res = await asyncFetch(obj, arg)
    fetch(obj.url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(obj.obj)
    })
      .then(res => res.json())
      .then(res => {
        console.log(res)
      })
    if (res.err === 0) {
      const content = '举报成功！'
      prompt('__native_call=>' + JSON.stringify({
        method: 'reqNative',
        action: 'alert',
        modul: 'alert',
        callbackId: 'callback', // 前端定义的一个回调接口
        args: {
          'success': 1,
          'content': content,
          'report': reportType === 1 ? 'article_report' : 'user_report'
        } // 参数(也是JSON 字符串)
      }))
    }
    else {
      const content = res.err_msg || '举报失败！'
      prompt('__native_call=>' + JSON.stringify({
        method: 'reqNative',
        action: 'alert',
        modul: 'alert',
        callbackId: 'callback', // 前端定义的一个回调接口
        args: {
          'success': 0,
          'content': content,
          'report': reportType === 1 ? 'article_report' : 'user_report'
        } // 参数(也是JSON 字符串)
      }))
    }
    // }
    // catch (error) {
    //   window.Qapp.showToast({ content: '网络错误' })
    // }
  }

  // 展示举报详情
  _renderReportD () {
    const { typeNum } = this.state

    if (!reportType || typeNum === 4) {
      return (
        <View className={style.reportSelect}>
          <View className={style.textH}>举报详情</View>
          <View>
            <textarea
              id = "input_id"
              className={style.inputText}
              maxLength={300}
              placeholder='请输入举报详情'
              onChange={this._ReportDetail}
            ></textarea>
          </View>
        </View>
      )
    }
  }

  // 展示上传图片
  _renderUploadImg () {
    const { typeNum } = this.state
    if (!reportType || typeNum === 6) {
      return (
        <View className={style.selectImg}>
          <View style={{ fontSize: '12px' }} className={style.textC}>请上传截图证据，经核实将立马撤销神原创或限制展示权限！
截图需包括原帖内容和发表时间。</View>
          <form className={style.formSubmit} encType="multipart/form-data">
            <View className={style.imgShow}>
              {this._handleImg()}
            </View>
            {this._renderImgChoose()}
          </form>
        </View>
      )
    }
  }

  // 举报类型
  _renderType () {
    const { report } = dataSource
    const { isSelsectType, typeNum } = this.state
    return report[reportType].map((item, index) => {
      return (
        <View className={isSelsectType && typeNum === index ? style.activeSelectList : style.selectList} tap={() => this._handleSelectType(index)} key={index}>{item}</View>
      )
    })
  }

  // 选择举报类型
  _handleSelectType (index) {
    this._inputBlur()
    this.setState({
      isSelsectType: true,
      typeNum: index
    })
  }

  // 添加图片预览
  _handleImg () {
    const { imgSource } = this.state
    // console.log(imgSource)
    return imgSource.map((item, index) => {
      return (
        <View className={style.upImg} key={index} style={{ backgroundImage: `url(${item})` }}>
          <View className={style.imgClose} tap={() => this._handleDelate(index)}></View>
        </View>
      )
    })
  }

  // 点击删除上传的图片
  _handleDelate (index) {
    const { imgSource } = this.state
    imgSource.splice(index, 1)
    this.setState({ imgSource })
  }

  // 控制展示添加图片按钮
  _renderImgChoose () {
    const isShowAdd = !(this.state.imgSource.length >= 4)
    if (isShowAdd) {
      return (
        <View className={style.imgChoose}>
          <View className={style.add}>+</View>
          <input type="file" className={style.xdaTanFileImg} accept="image/*" multiple="multiple" name="fileAttach" onChange={this.handleChange}/>
        </View>
      )
    }
  }

  // 选择图片，马上预览
  handleChange (e) {
    const fl = e.target.files.length
    for (let i = 0; i < fl; i++) {
      const file = e.target.files[i]
      const size = file.size / 1024
      if (size > 1024 * 4) {
        window.Qapp.showToast({ content: '图片大小不能超过4兆！' })
        file.value = ''
        return false
      }
      else if (size <= 0) {
        window.Qapp.showToast({ content: '图片大小不能为0！' })
        file.value = ''
        return false
      }
      const reader = new FileReader()

      // 读取文件过程方法

      reader.onloadstart = function (e) {
      // console.log("开始读取....");
      }
      reader.onprogress = function (e) {
      // console.log("正在读取中....");
      }
      reader.onabort = function (e) {
        console.log('中断读取....')
      }
      reader.onerror = function (e) {
        console.log('读取异常....')
      }
      reader.onload = (e) => {
      // console.log("成功读取....");
        const { imgSource } = this.state
        if (imgSource.length >= 4) {
          window.Qapp.showToast({ content: '最多只能上传4张图片哦！' })
          return false
        }
        // console.log(e.target)
        imgSource.push(e.target.result)
        this.setState({ imgSource })
      }
      reader.readAsDataURL(file)
    }
  }
  render () {
    return (
      <View className={style.container}>
        <ScrollView className={style.scrollContainer} scrollbars='false'>
          <View className={style.headerName} tap = {this._inputBlur}>
            <View className={style.textC}>正在举报{user}：</View>
            {reportType === 0
              ? <img src={dataSource.reportInfo.avatar}
                className={style.userIcon}/> : ''}
            <Text className={style._textC}>{dataSource.reportInfo.content}</Text>
          </View>
          <View className={style.reportSelect}>
            <View className={style.textH}>举报类型</View>
            <View className={style.selects}>
              {this._renderType()}
            </View>
          </View>
          {this._renderReportD()}
          {this._renderUploadImg()}
          <View
            id = "myDiv"
            tap = {this._handleSubit}
            className={this.state.isSelsectType ? style.submitButSet : style.submitBut}>提交举报</View>
        </ScrollView>
      </View>
    )
  }
}

export default Index

